<?php
defined('InShopNC') or exit('Access Invalid!');

/*HTML安全过滤*/
function _htmtocode($content) {
    $content = str_replace('%','%&lrm;',$content);
    $content = str_replace("<", "&lt;", $content);
    $content = str_replace(">", "&gt;", $content);
    $content = str_replace("\n", "<br/>", $content);
    $content = str_replace(" ", "&nbsp;", $content);
    $content = str_replace('"', "&quot;", $content);
    $content = str_replace("'", "&#039;", $content);
    $content = str_replace("$", "&#36;", $content);
    $content = str_replace('}','&rlm;}',$content);
    return $content;
}

function _width($p,$t,$w){
    if($p<=0){return false;}
    return $p/$t*$w;
}

function _idjia($id){
    return $id+1000000000;
}

function yunma($ma,$html="span"){
    $list=explode(",",$ma);
    $st="";
    foreach($list as $list2){
        $st.="<".$html.">".$list2."</".$html.">";
    }
    return $st;
}

/* 网络操作函数 */
function _g_triggerRequest($url,$io=false,$post_data = array(), $cookie = array())
{
    $method = empty($post_data) ? 'GET' : 'POST';

    $url_array = parse_url($url);
    $port = isset($url_array['port']) ? $url_array['port'] : 80;

    if (function_exists('fsockopen')) {
        $fp = @fsockopen($url_array['host'], $port, $errno, $errstr, 30);
    } elseif (function_exists('pfsockopen')) {
        $fp = @pfsockopen($url_array['host'], $port, $errno, $errstr, 30);
    } elseif (function_exists('stream_socket_client')) {
        $fp = @stream_socket_client($url_array['host'] . ':' . $port, $errno, $errstr, 30);
    } else {
        $fp = false;
    }

    if (!$fp) {
        return false;
    }

    $url_array['query'] =  isset($url_array['query']) ? $url_array['query'] : '';
    $getPath = $url_array['path'] ."?". $url_array['query'];

    $header  = $method . " " . $getPath." ";
    $header .= "HTTP/1.1\r\n";
    $header .= "Host: ".$url_array['host']."\r\n"; //HTTP 1.1 Host域不能省略
    $header .= "Pragma: no-cache\r\n";

    /*
        //以下头信息域可以省略
        $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 \r\n";
        $header .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,q=0.5 \r\n";
        $header .= "Accept-Language: en-us,en;q=0.5 ";
        $header .= "Accept-Encoding: gzip,deflate\r\n";
    */


    if(!empty($cookie)){
        $_cookie_s = strval(NULL);
        foreach($cookie as $k => $v){
            $_cookie_s .= $k."=".$v."; ";
        }
        $_cookie_s = rtrim($_cookie_s,"; ");
        $cookie_str =  "Cookie: " . base64_encode($_cookie_s) ." \r\n";	   //传递Cookie
        $header .= $cookie_str;
    }
    $post_str = '';
    if(!empty($post_data)){
        $_post = strval(NULL);
        foreach($post_data as $k => $v){
            $_post .= $k."=".urlencode($v)."&";
        }
        $_post = rtrim($_post,"&");
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";//POST数据
        $header .= "Content-Length: ". strlen($_post) ." \r\n";//POST数据的长度

        $post_str = $_post."\r\n"; //传递POST数据
    }
    $header .= "Connection: Close\r\n\r\n";
    $header .= $post_str;

    fwrite($fp,$header);
    if($io){
        while (!feof($fp)){
            echo fgets($fp,1024);
        }
    }
    fclose($fp);
    //echo $header;
    return true;
}



/*
 * 取得产品图片
 * @param $id
 */
function shopimg($id){
    $param = array();
    $param['table'] = 'crowdlist';
    $param['where'] = 'id='.$id;
    $param['order'] = 'id DESC';
    $result = Db::select($param);
    return UPLOAD_SITE_URL.DS.ATTACH_GOODS.DS.$result[0]['thumb'];
}

function get_user_avatar($q_user){
    return $q_user['member_avatar'] ? UPLOAD_SITE_URL.DS.ATTACH_AVATAR.DS.$q_user['member_avatar']:UPLOAD_SITE_URL.DS.ATTACH_AVATAR.DS."member.jpg";
}

function get_user_name($q_user){
    if(!empty($q_user['member_nickname'])) {
        return $q_user['member_nickname'];
    }elseif(!empty($q_user['member_mobile'])){
        return 'mu'. substr($q_user['member_mobile'],-4);
    }elseif(!empty($q_user['member_email'])){
        return $q_user['member_email'];
    }else{
        return $q_user['member_name'];
    }
}

function get_ip($ip,$ipmac=null){
    $ip=explode(',',$ip);
    if($ipmac=='ipmac'){
        return $ip[1];
    }elseif($ipmac=='ipcity'){
        return $ip[0];
    }
}

//生成订单号
function pay_get_dingdan_code($dingdanzhui=''){
    return $dingdanzhui.time().substr(microtime(),2,6).rand(0,9);
}

/*
*   生成购买的云购码
*	user_num 		@生成个数
*	shopinfo		@商品信息
*	ret_data		@返回信息
*/
function pay_get_shop_codes($user_num=1,$shopinfo=null,&$ret_data=null,$model=null,$obj=null){
    $ret_data['query'] = true;
    $table = $shopinfo['codes_table'];
    $codes_arr = array();
    $codes_one =  $model->table($table)->field("id,s_id,s_cid,s_len,s_codes")->where(array('s_id'=>$shopinfo['id']))->order("s_cid DESC")->find();
    $codes_arr[$codes_one['s_cid']] = $codes_one;
    $codes_count_len = $codes_arr[$codes_one['s_cid']]['s_len'];

    if($codes_count_len < $user_num && $codes_one['s_cid'] > 1){
        for($i=$codes_one['s_cid']-1;$i>=1;$i--) {
            $codes_arr[$i] = $model->table($table)->field("id,s_id,s_cid,s_len,s_codes")->where(array('s_id' => $shopinfo['id'], 's_cid' => $i))->order("s_cid DESC")->find();
            $codes_count_len += $codes_arr[$i]['s_len'];
            if ($codes_count_len > $user_num) break;
        }
    }

    if($codes_count_len < $user_num) $user_num = $codes_count_len;

    $ret_data['user_code'] = '';
    $ret_data['user_code_len'] = 0;

    foreach($codes_arr as $icodes){
      if($icodes) {
          $u_num = $user_num;
          $icodes['s_codes'] = unserialize($icodes['s_codes']);
          $code_tmp_arr = array_slice($icodes['s_codes'], 0, $u_num);
          $ret_data['user_code'] .= implode(',', $code_tmp_arr);
          $code_tmp_arr_len = count($code_tmp_arr);

          if ($code_tmp_arr_len < $u_num) {
              $ret_data['user_code'] .= ',';
          }

          $icodes['s_codes'] = array_slice($icodes['s_codes'], $u_num, count($icodes['s_codes']));
          $icode_sub = count($icodes['s_codes']);
          $icodes['s_codes'] = serialize($icodes['s_codes']);

          if (!$icode_sub) {
              $query = $model->table($table)->where(array('id' => $icodes['id']))->update(array('s_cid' => 0, 's_codes' => $icodes[s_codes], 's_len' => $icode_sub));
              if (!$query) $ret_data['query'] = false;
          } else {
              $query = $model->table($table)->where(array('id' => $icodes['id']))->update(array('s_codes' => $icodes[s_codes], 's_len' => $icode_sub));
              if (!$query) $ret_data['query'] = false;
          }
          $ret_data['user_code_len'] += $code_tmp_arr_len;
          $user_num = $user_num - $code_tmp_arr_len;
      }
    }
    return $ret_data;
}

function microt($time,$x=null){
    $len=strlen($time);
    if($len<13){
        $time=$time."0";
    }
    $list=explode(".",$time);
    if($x=="L"){
        return date("His",$list[0]).substr($list[1],0,3);
    }else if($x=="Y"){
        return date("Y-m-d",$list[0]);
    }else if($x=="H"){
        return date("H:i:s",$list[0]).".".substr($list[1],0,3);
    }else if($x=="r"){
        return date("Y年m月d日 H:i",$list[0]);
    }else{
        return date("Y-m-d H:i:s",$list[0]).".".substr($list[1],0,3);
    }
}

function _put_time($time = 0,$test=''){
    if(empty($time)){return $test;}
    $time = substr($time,0,10);
    $ttime = time() - $time;
    if($ttime <= 0 || $ttime < 60){
        return '几秒前';
    }
    if($ttime > 60 && $ttime <120){
        return '1分钟前';
    }

    $i = floor($ttime / 60);							//分
    $h = floor($ttime / 60 / 60);						//时
    $d = floor($ttime / 86400);							//天
    $m = floor($ttime / 2592000);						//月
    $y = floor($ttime / 60 / 60 / 24 / 365);			//年
    if($i < 30){
        return $i.'分钟前';
    }
    if($i > 30 && $i < 60){
        return '一小时内';
    }
    if($h>=1 && $h < 24){
        return $h.'小时前';
    }
    if($d>=1 && $d < 30){
        return $d.'天前';
    }
    if($m>=1 && $m < 12){
        return $m.'个月前';
    }
    if($y){
        return $y.'年前';
    }
    return "";

}

/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function _strcut($string, $length,$dot = '...') {
    $string = trim($string);
    if($length && strlen($string) > $length) {
        //截断字符
        $wordscut = '';
        if(strtolower(G_CHARSET) == 'utf-8') {
            //utf8编码
            $n = 0;
            $tn = 0;
            $noc = 0;
            while ($n < strlen($string)) {
                $t = ord($string[$n]);
                if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1;
                    $n++;
                    $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif(224 <= $t && $t < 239) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) {
                    break;
                }
            }
            if ($noc > $length) {
                $n -= $tn;
            }
            $wordscut = substr($string, 0, $n);
        } else {
            for($i = 0; $i < $length - 1; $i++) {
                if(ord($string[$i]) > 127) {
                    $wordscut .= $string[$i].$string[$i + 1];
                    $i++;
                } else {
                    $wordscut .= $string[$i];
                }
            }
        }
        $string = $wordscut.$dot;
    }
    return trim($string);
}

function tencord($time,$num,$shopid,$qishu){
    $record = $this->table('member_go_record')->where(array('time'=>$time))->find();
    $recordm = $this->table('member_go_record')->where(array('id'=>array('neq',$record['id'])))->limit(100)->select();
    $s=0;
    foreach($recordm as $record){
        $list=explode(" ",$record['time']);
        $dat=date("His",$list[1]).substr($list[0],2,2);
        $s=$s+$dat;
    }
    $huode=10000000+$s%$num;
    $shopqishu= $this->table('member_go_record')->where(array('shopid'=>$shopid,'shopqishu'=>$qishu))->select();

    foreach($shopqishu as $shopqi){
        $goucodex=strpos($shopqi['goucode'],"$huode");
        if(!is_bool($goucodex)){
            $this->table("member_go_record")->where(array('shopid'=>$shopid,'shopqishu'=>$qishu,'member_id'=>$shopqi['member_id']))->update(array('huode'=>$huode));
        }
    }
    $qishu=$qishu+1;
    $this->table("crowdlist")->where(array('id'=>$shopid))->update(array('canyurenshu'=>0,'qishu'=>$qishu));
}



function go_record($model,$obj){
    $Cartlist=json_decode(stripslashes($_COOKIE['Cartlist']),true);
    $shopids=array();			//商品ID
    if(is_array($Cartlist)){
        foreach($Cartlist as $key => $val){
            if($key!=0) {
                $shopids[] = intval($key) ;
            }
        }
    }
    $shoplist=array();		//商品信息
    if($shopids!=NULL){
        $shoplist= $model->table("crowdlist")->where(array('id'=>array('in',$shopids),'q_uid'=>array('exp','q_uid is null')))->select();
    }else{
        $obj['ok'] = '购物车内没有商品!';
        return $obj;
    }

    $MoenyCount= 0;
    $shopguoqi = 0;
    if(count($shoplist)>=1){
        $scookies_arr = array();
        $scookies_arr['MoenyCount'] = 0;
        foreach($Cartlist as $key => $val){
            $key=intval($key);
            for($i=0;$i<count($shoplist);$i++) {
                if ($shoplist[$i]['id']==$key) {
                    if ($shoplist[$i]['shenyurenshu'] != 0) {
                        if (($shoplist[$i]['xsjx_time'] != '0') && $shoplist[$i]['xsjx_time'] < time()) {
                            unset($shoplist[$i]);
                            $shopguoqi = 1;
                            continue;
                        }
                        $shoplist[$i]['cart_gorenci'] = $val['num'] ? $val['num'] : 1;
                        if ($shoplist[$i]['cart_gorenci'] >= $shoplist[$i]['shenyurenshu']) {
                            $shoplist[$i]['cart_gorenci'] = $shoplist[$i]['shenyurenshu'];
                        }
                        $MoenyCount += $shoplist[$i]['yunjiage'] * $shoplist[$i]['cart_gorenci'];
                        $shoplist[$i]['cart_xiaoji'] = substr(sprintf("%.3f", $shoplist[$i]['yunjiage'] * $shoplist[$i]['cart_gorenci']), 0, -1);
                        $shoplist[$i]['cart_shenyu'] = $shoplist[$i]['zongrenshu'] - $shoplist[$i]['canyurenshu'];
                        $scookies_arr[$key]['shenyu'] = $shoplist[$i]['cart_shenyu'];
                        $scookies_arr[$key]['num'] = $shoplist[$i]['cart_gorenci'];
                        $scookies_arr[$key]['money'] = intval($shoplist[$i]['yunjiage']);
                        $scookies_arr['MoenyCount'] += intval($shoplist[$i]['cart_xiaoji']);
                    }
                }
            }
        }
        if(count($shoplist) < 1){
            $scookies_arr = '0';
            if($shopguoqi){
                $obj['ok'] = '限时揭晓过期商品不能购买!';
                return $obj;
            }else{
                $obj['ok'] = '购物车里没有商品!';
                return $obj;
            }
        }
    }else{
        $scookies_arr = '0';
        $obj['ok'] = '购物车里商品已经卖完或已下架!';
        return $obj;
    }

    $obj['MoenyCount']=substr(sprintf("%.3f",$MoenyCount),0,-1);

    /*总支付价格*/
    $obj['shoplist']=$shoplist;
    $obj['scookies_arr'] = $scookies_arr;
    $obj['ok'] = 'ok';
    return $obj;
}

/**
 *	开始支付
 **/
function go_pay($model,$obj,$pay_checkbox){
    if($obj['members']['money'] >= $obj['MoenyCount']){
        foreach($obj['shoplist'] as $shop){
            pay_insert_shop($shop, 'add',$model,$obj);
        }
        $pay_1 =  pay_bag($model,$obj);
        return $pay_1;
    }
    exit;
}

function pay_bag($model,$obj){
    $time=time();
    $member_id=$obj['members']['member_id'];
    $obj = set_dingdan('账户','A',$model,$obj);

    /*会员购买过账户剩余金额*/
    $Money = $obj['members']['money'] - $obj['MoenyCount'];
    $pay_zhifu_name = '账户';

    //更新用户账户金额
    if($Money<=$obj['members']['available_rc_balance']){
        $model->table('member')->where(array('member_id'=>$member_id))->update(array('available_rc_balance'=>$Money));
    }else{
        if($obj['members']['available_rc_balance'])$model->table('member')->where(array('member_id'=>$member_id))->update(array('available_rc_balance'=>0));
        $Money = $Money - $obj['members']['available_rc_balance'];
        $model->table('member')->where(array('member_id'=>$member_id))->update(array('available_predeposit'=>$Money));
    }
    $obj['members']['money'] = $Money;

    
    $goods_count_num = 0;
    foreach($obj['shoplist'] as $shop) {
        $query_4 = $model->table("member_go_account")->insert(array('member_id'=>$member_id,'type'=>'-1','pay'=>$pay_zhifu_name,'content'=>'云购了商品 '.$shop['title'],'money'=>1,'time'=>$time));
        if ($shop['canyurenshu'] >= $shop['zongrenshu'] && $shop['maxqishu'] >= $shop['qishu']) {
            //$model->table('crowdlist')->where(array('id' => $shop['id']))->update(array('canyurenshu' => array('exp', '`canyurenshu`=`zongrenshu`', 'shenyurenshu' => 0)));

        } else {
            $shenyurenshu = $shop['zongrenshu'] - $shop['canyurenshu'];
            $query = $model->table('crowdlist')->where(array('id' => $shop['id']))->update(array('canyurenshu' => $shop['canyurenshu'], 'shenyurenshu' => $shenyurenshu));
            if (!$query) $query_5 = false;
        }
        $goods_count_num += $shop['goods_count_num'];
    }

    $dingdancode=$obj['dingdancode'];

    $query_6 = $model->table('member_go_record')->where(array('member_id'=>$member_id,'code'=>$dingdancode))->update(array('status'=>'已付款,未发货,未完成'));
    $query_7 = $obj['dingdan_query'];
    $obj['goods_count_num'] = $goods_count_num;

    if($query_4 && $query_6 && $query_7){
            foreach($obj['shoplist'] as $shop) {
                if ($shop['canyurenshu'] >= $shop['zongrenshu'] && $shop['maxqishu'] >= $shop['qishu']) {
                    $query_insert = pay_insert_shop($shop, 'add',$model,$obj);
                   // $model->table('crowdlist')->where(array('id'=>$shop['id']))->update(array('canyurenshu'=>array('exp','canyurenshu=zongrenshu'),'shenyurenshu'=>0));
                }
            }
           return true;
    }else{
        return  false;
    }
}

/*获取客户端ip*/
function _get_ip(){
    if (isset($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], "unknown"))
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], "unknown"))
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if (isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else if (isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else $ip = "";
    return ($ip);
}

function _get_ip_dizhi($ip=null){
    $opts = array(
        'http'=>array(
            'method'=>"GET",
            'timeout'=>5,)
    );
    $context = stream_context_create($opts);


    if($ip){
        $ipmac = $ip;
    }else{
        $ipmac=_get_ip();
        if(strpos($ipmac,"127.0.0.") === true)return '';
    }

    $url_ip='http://ip.taobao.com/service/getIpInfo.php?ip='.$ipmac;
    $str = @file_get_contents($url_ip, false, $context);
    if(!$str) return "";
    $json=json_decode($str,true);
    if($json['code']==0){

        $json['data']['region'] = addslashes(_htmtocode($json['data']['region']));
        $json['data']['city'] = addslashes(_htmtocode($json['data']['city']));

        $ipcity= $json['data']['region'].$json['data']['city'];
        $ip= $ipcity.','.$ipmac;
    }else{
        $ip="";
    }
    return $ip;
}

function set_dingdan($pay_type='',$dingdanzhui='',$model,$obj){
    $member_id=$obj['members']['member_id'];
    $uphoto = str_replace(BASE_SITE_URL,'',get_user_avatar($obj['members']));
    $username = addslashes(get_user_name($obj['members']));
    $insert_html='';
    $obj['dingdancode'] = $dingdancode= pay_get_dingdan_code($dingdanzhui);		//订单号

    if(count($obj['shoplist'])>1){
        $dingdancode_tmp = 1;	//多个商品相同订单
    }else{
        $dingdancode_tmp = 0;	//单独商品订单
    }

    $ip =  _get_ip_dizhi($obj['members']['member_login_ip']);

    /*订单时间*/
    $time=sprintf("%.3f",microtime(true));
    $obj['MoenyCount']=0;
    $obj['insert_id'] = array();
    foreach($obj['shoplist'] as $key=>$shop){
        $ret_data = array();
        $ret_data = pay_get_shop_codes($shop['cart_gorenci'],$shop,$ret_data,$model,$obj);
        if(!$ret_data['user_code']){
            content_get_go_codes($shop['zongrenshu'],$shop['zongrenshu'],$shop['id'],$model,$obj);
            $ret_data = pay_get_shop_codes($shop['cart_gorenci'],$shop,$ret_data,$model,$obj);
        }

        $obj['dingdan_query'] = $ret_data['query'];
        if(!$ret_data['query'])$obj['dingdan_query'] = false;
        $codes = $ret_data['user_code'];									//得到的云购码
        $codes_len= intval($ret_data['user_code_len']);						//得到云购码个数
        $money=$codes_len * $shop['yunjiage'];								//单条商品的总价格
        $obj['MoenyCount'] += $money;										//总价格
        $status='未付款,未发货,未完成';
        $shop['canyurenshu'] = intval($shop['canyurenshu']) + $codes_len;
        $shop['goods_count_num'] = $codes_len;
        $shop['title'] = addslashes($shop['title']);

        $obj['shoplist'][$key] = $shop;
        $insert_id = $model->table("member_go_record")->insert(array('code'=>$dingdancode,'code_tmp'=>$dingdancode_tmp,'member_id'=>$member_id,'username'=>$username,'uphoto'=>$uphoto,'shopid'=>$shop['id'],'shopname'=>$shop[title],'shopqishu'=>$shop[qishu],'gonumber'=>$codes_len,'moneycount'=>$money,'goucode'=>$codes,'pay_type'=>$pay_type,'ip'=>$ip,'status'=>$status,'time'=>$time));
        $obj['insert_id'][] = $insert_id;
    }
    return $obj;
}


/*
	揭晓与插入商品
	@shop   商品数据
*/
function pay_insert_shop($shop='',$type='',$model,$obj){
    $time=sprintf("%.3f",microtime(true)+(int)30);

    if($shop['xsjx_time'] != '0'){
        return $model->table('crowdlist')->where(array('id'=>$shop['id']))->update(array('canyurenshu'=>array('exp','canyurenshu = zongrenshu'),'shenyurenshu'=>0));
    }
    $num = $shop['zongrenshu']>100 ? 100 : $shop['zongrenshu'];
    $obj['shopid'] = $shop['id'];
    $obj = run_tocode($time,$num,$shop['canyurenshu'],$model,$obj);
    $code = $obj['go_code'];

    //ksg20140901新增，判断是否指定中奖//
    if($shop['zhiding']){
        $ex_info= $model->table("member_go_record")->where(array('shopid'=>$shop['id'],'shopqishu'=>$shop['qishu'],'member_id'=>$shop['zhiding']))->find();
        $ex_code=explode(",",$ex_info['goucode']);

        if($ex_code[0]){
            $tempinfo = $model->table("member_go_record")->where(array('shopid'=>$shop['id'],'shopqishu'=>$shop['qishu'],'goucode'=>array('exp','goucode LIKE  \'%'.$code.'%\'')))->find();
            //本来的中奖码对应的记录
            $str=str_replace($code,$ex_code[0],$tempinfo['goucode']);
            $model->table("member_go_record")->where(array('id'=>$tempinfo['id']))->update(array('goucode'=>$str));
            //将系统原来的中奖吗对应的购买记录换成指定中奖会员购买的code
            $str2=str_replace($ex_code[0],$code,$ex_info['goucode']);
            $model->table("member_go_record")->where(array('id'=>$ex_info['id']))->update(array('goucode'=>$str2));
            //将指定中奖会员的购买记录中的code换成系统计算出来的中奖吗
        }
    }

    /////////////////
    $counttime = $obj['count_time'];
    $u_go_info = $model->table("member_go_record")->where(array('shopid'=>$shop['id'],'shopqishu'=>$shop['qishu'],'goucode'=>array('exp','goucode LIKE  \'%'.$code.'%\'')))->find();
    $content = $u_go_info;
    $u_info = $model->table("member")->where(array('member_id'=>$u_go_info['member_id']))->field("member_id,member_nickname as username,member_email,member_mobile,member_avatar")->find();

    //更新商品
    $query = true;
    if($u_info){
        $u_info['username'] = _htmtocode($u_info['username']);
        $q_user = serialize($u_info);
        $gtimes = 0;
        if($gtimes == 0 || $gtimes == 1){
            $q_showtime = 'N';
        }else{
            $q_showtime = 'Y';
        }
        $q = $model->table("crowdlist")->where(array('id'=>$shop['id']))->update(array('canyurenshu'=>$shop['zongrenshu'],'shenyurenshu'=>0,'q_uid'=>$u_info['member_id'],'q_user'=>$q_user,'q_user_code'=>$code,'q_content'=>$content,'q_counttime'=>$counttime,'q_end_time'=>$time,'q_showtime'=>$q_showtime));
        if(!$q)$query = false;
        if($q){
            $q = $model->table("member_go_record")->where(array('id'=>$u_go_info['id'],'code'=>$u_go_info['code'],'member_id'=>$u_go_info['member_id'],'shopid'=>$shop['id'],'shopqishu'=>$shop['qishu']))->update(array('huode'=>$code));
            if(!$q) {
                $query = false;
            }else{
                $post_arr= array("member_id"=>$u_info['member_id'],"gid"=>$shop['id'],"send"=>1);
                send_Notice_code($post_arr,$model,$obj);
                if($shop['qishu'] < $shop['maxqishu']){
                    $maxinfo = $this->table('crowdlist')->where(array('sid'=>$shop['sid']))->order("qishu DESC")->find();
                    $intall = content_add_shop_install($maxinfo,false);
                    if(!$intall) return $query;
                }
                $query = true;
            }
        }else{
            $query =  false;
        }
    }else{
        $query =  false;
    }
    return $query;
}



function run_tocode($time='',$num=100,$cyrs='233',$model,$obj){
    if(empty($time))return false;
    if(empty($num))return false;
    $obj['times'] = $time;
    $obj['num'] = $num;
    $obj['cyrs'] = $cyrs;
    return get_code_user_html($model,$obj);
}

function get_code_user_html($model,$obj){
    $time = $obj['times'];
    $num  = $obj['num'];
    $obj['go_list'] = $model->table('member_go_record')->where(array('time'=>array('exp','time<\''.$time.'\''),'shopid'=>$obj['shopid']))->order('id DESC')->limit($num)->select();
    if($obj['go_list']  && count($obj['go_list']) >= $obj['num']){
      return  get_code_dabai($obj);
    }else{
     return  get_code_yibai($obj);
    }
}

function get_code_dabai($obj){
    $go_list = $obj['go_list'];
    $html=array();
    $count_time = 0;
    foreach($go_list as $key=>$v){
        $html[$key]['time'] = $v['time'];
        $html[$key]['username'] = $v['username'];
        $html[$key]['member_id'] = $v['member_id'];
        $html[$key]['shopid'] = $v['shopid'];
        $html[$key]['shopname'] = $v['shopname'];
        $html[$key]['shopqishu'] = $v['shopqishu'];
        $html[$key]['gonumber'] = $v['gonumber'];
        $h=abs(date("H",$v['time']));
        $i=date("i",$v['time']);
        $s=date("s",$v['time']);
        list($time,$ms) = explode(".",$v['time']);
        $time = $h.$i.$s.$ms;
        $html[$key]['time_add'] = $time;
        $count_time += $time;
    }
    $obj['go_content'] = serialize($html);
    $obj['count_time'] = $count_time;
    $obj['go_code'] = 10000001+fmod($count_time,$obj['cyrs']);
    return $obj;
}

function get_code_yibai($obj){
    $time = $obj['times'];
    $cyrs = $obj['cyrs'];
    $h=abs(date("H",$time));
    $i=date("i",$time);
    $s=date("s",$time);
    $w=substr($time,11,3);
    $num= $h.$i.$s.$w;
    if(!$cyrs)$cyrs=1;
    $obj['go_code'] = 10000001+fmod($num*100,$cyrs);
    $obj['go_content'] = false;
    return $obj;
}

/*
 新建一期商品
 info 	 商品的ID 或者 商品的数组
 使用此函数注意传进来的的商品期数不等于最大期数
 autocommit @是否开启事物
*/
function content_add_shop_install($info=null,$autocommit=true,$model,$obj)
{
    try {
        $model->beginTransaction();
        unset($info['id']);
        unset($info['q_uid']);
        unset($info['q_user']);
        unset($info['q_user_code']);
        unset($info['q_content']);
        unset($info['q_counttime']);
        unset($info['q_end_time']);
        unset($info['def_renshu']);
        unset($info['order']);

        $info['xsjx_time'] = 0;
        $info['time'] = time();
        $info['qishu'] = intval($info['qishu']);
        $info['qishu']++;
        $info['canyurenshu'] = '0';
        $info['shenyurenshu'] = $info['zongrenshu'];
        $info['codes_table'] = content_get_codes_table();
        $info['q_showtime'] = 'N';
        $info['title'] = _htmtocode($info['title']);
        $info['title2'] = _htmtocode($info['title2']);
        $insert_id = $model->table('crowdlist')->insert($info);
        if(!empty($insert_id))content_get_go_codes($info['zongrenshu'], 3000, $insert_id, $model, $obj);
        $model->commit();
        return $insert_id;
    } catch (Exception $e) {
        $model->rollback();
        return false;
    }
}

    /*
	计算云购码表
*/
    function content_get_codes_table(){
        $num = C('shopcodes_table');
        $table = 'member_go_shopcodes_'.$num;
        $shopcodes_table = DB::getAll("SHOW TABLE STATUS LIKE '".DBPRE.$table."'");

        if(!$shopcodes_table || !$num) return false;
        if($shopcodes_table['Auto_increment'] >=99999){
            $num = $num+1;
            $shopcodes_table = 'member_go_shopcodes_'.$num;
            $q1 = DB::query("CREATE TABLE `".DBPRE.$shopcodes_table."` (
				  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
				  `s_id` int(10) unsigned NOT NULL,
				  `s_cid` smallint(5) unsigned NOT NULL,
				  `s_len` smallint(5) DEFAULT NULL,
				  `s_codes` text,
				  `s_codes_tmp` text,
				  PRIMARY KEY (`id`),
				  KEY `s_id` (`s_id`),
				  KEY `s_cid` (`s_cid`),
				  KEY `s_len` (`s_len`)
				) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
		");
            $q2 = DB::query("UPDATE `".DBPRE.'setting'."` SET `value` = '$num' where `key` = 'shopcodes_table'");
            if(!$q1 || !$q2)return false;
        }else{
            $num = intval($num['value']);
            $shopcodes_table = 'member_go_shopcodes_'.$num;
        }
        return $shopcodes_table;

    }
/*
   生成云购码
   CountNum @ 生成个数
   len 	    @ 生成长度
   sid	    @ 商品ID
*/
function content_get_go_codes($CountNum=null,$len=null,$sid=null,$model,$obj){
    $table = 'member_go_shopcodes_1';
    $num = ceil($CountNum/$len);
    $code_i = $CountNum;
    if($num == 1){
        $codes=array();
        for($i=1;$i<=$CountNum;$i++){
            $codes[$i]=10000000+$i;
        }shuffle($codes);$codes=serialize($codes);
        $query = $model->table($table)->insert(array('s_id'=>$sid,'s_cid'=>1,'s_len'=>$CountNum,'s_codes'=>$codes,'s_codes_tmp'=>$codes));
        unset($codes);
        return $query;
    }
    $query_1 = true;
    for($k=1;$k<$num;$k++){
        $codes=array();
        for($i=1;$i<=$len;$i++){
            $codes[$i]=10000000+$code_i;
            $code_i--;
        }shuffle($codes);$codes=serialize($codes);
        $query_1 = $model->table($table)->insert(array('s_id'=>$sid,'s_cid'=>$k,'s_len'=>$len,'s_codes'=>$codes,'s_codes_tmp'=>$codes));
        unset($codes);
    }
    $CountNum = $CountNum - (($num-1)*$len);
    $codes=array();
    for($i=1;$i<=$CountNum;$i++){
        $codes[$i]=10000000+$code_i;
        $code_i--;
    }shuffle($codes);$codes=serialize($codes);
    $query_2 = $model->table($table)->insert(array('s_id'=>$sid,'s_cid'=>$num,'s_len'=>$CountNum,'s_codes'=>$codes,'s_codes_tmp'=>$codes));
    unset($codes);
    return $query_1 && $query_2;
}

/*
		@type  1 邮件
		@type  2 手机
		@type  3 邮件,手机
	*/
function send_Notice_code($params,$model,$obj){

    if(!isset($params['send']) && !isset($params['member_id']) && !isset($params['gid'])){
        return false;
    }
    $member_id = abs($params['member_id']);
    $gid = abs($params['gid']);

    $sendinfo = $model->table('sms_notice')->where(array('member_id'=>$member_id,'gid'=>$gid))->field('id,send_type')->find();
    if($sendinfo)return false;
    $member = $model->table('member')->where(array('member_id'=>$member_id))->find();
    if(!$member)return false;
    $info = $model->table('crowdlist')->where(array('id'=>$gid,'q_uid'=>$member_id))->field("id,q_user_code,q_end_time,title,q_user")->find();
    if(!$info)return false;

    $username = get_user_name($member);
    send_insert($member_id,$gid,$username,$info['title'],'-1',$model);

    $type = 2;
    $ret_send = false;
    if($type=='2'){
        if(!empty($member['member_mobile'])){
            $ret_send = send_mobile_shop_code($member['member_mobile'],$info['q_user_code']);
        }
    }
    if($ret_send){
        send_insert($member_id,$gid,$username,$info['title'],$type,$model);
    }
    exit(0);
}

function send_insert($member_id,$gid,$username,$shoptitle,$send_type,$model){
    $time=time();
    if($send_type == '-1'){
        $model->table("sms_notice")->insert(array('member_id'=>$member_id,'gid'=>$gid,'username'=>$username,'shoptitle'=>$shoptitle,'send_type'=>$send_type,'time'=>$time));
    }else{
        $model->table('sms_notice')->where(array('member_id'=>$member_id,'gid'=>$gid))->update(array('send_type'=>$send_type));
    }
}

function  get_record($model,$member_id,$item_id,$limit){
    return $model->table('member_go_record')->where(array('member_id'=>$member_id,'shopid'=>$item_id,'status'=>array('LIKE','%已付款%')))->order("id DESC")->limit($limit)->select();
}



/**
 *	发送用户手机获奖短信
 *	mobile @用户手机号
 *   uid    @用户的ID
 *	code   @中奖码
 */

function send_mobile_shop_code($mobile=null,$code=null){
    if(!$mobile)showMessage("发送用户手机获奖短信,手机号码不能为空!");
    if(!$code)showMessage("发送用户手机获奖短信,中奖码不能为空!");

    $content = "恭喜你金银拼用户！您在金银商城购买的商品已揭晓,获得的幸运码为：00000000 请登陆网站查看详情！请尽快联系管理员发货！";
    $content= str_ireplace("00000000",$code,$content);

    $sms = new Sms();
    $result = $sms->send($mobile,$content);
    return $result;
}
